from decimal import Decimal
from rest_framework.filters import OrderingFilter
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView,ListAPIView,UpdateAPIView,RetrieveAPIView
from django_redis import get_redis_connection
from goods.models import SKU
# Create your views here.
from orders.models import OrderGoods,OrderInfo
from orders.serializers import OrderSerializer, OrderSaveSerializer, OrderListSerializer,OrderGoodsSerializer, \
    UpdateCommentSerializer
from orders.utils import OrderPageNum


class OrderShowView(APIView):

    def get(self,request):

        user = request.user
        #返回参数 sku,count, freight
        conn = get_redis_connection('cart')
        sku_count = conn.hgetall('cart_%s'%user.id)
        sku_ids = conn.smembers('cart_select_%s'%user.id) # {b'8',b'9'}
        sku_dict = {}
        for sku in sku_ids:
            sku_dict[int(sku)] = int(sku_count[sku])
        skus = SKU.objects.filter(id__in=sku_dict.keys())
        for sku in skus:
            sku.count = sku_dict[sku.id]

        freight = Decimal(10)

        ser = OrderSerializer({'freight':freight,'skus':skus})

        return Response(ser.data)


class OrdersView(CreateAPIView,ListAPIView):

    permission_classes = [IsAuthenticated]

    # serializer_class = OrderSaveSerializer

    # filter_backends = [OrderingFilter]
    # Ordering_fields = ('create_time')
    pagination_class = OrderPageNum
    # queryset = OrderGoods.objects.all()

    def get_queryset(self):

        user = self.request.user
        # order = OrderGoods.objects.filter(order__user=user)
        # return OrderGoods.objects.filter(order__user=user.id)
        try:
            OrderInfo.objects.filter(user=user.id)
        except:
            return Response({'message':'用户不存在'})

        return OrderInfo.objects.filter(user=user.id)

    # def list(self, request, *args, **kwargs):
    #
    #     queryset = self.filter_queryset(self.get_queryset())
    #     orderInfo = OrderInfo.objects.filter(user=request.user.id)
    #
    #     # order_dict = {}
    #     # for order in ordergood:
    #     #     order_dict[order]=order.order_id
    #     #     order_dict[order]['skus'] = order.sku
    #     #     order_dict[order]['skus']['sku'] = order.sku.name
    #     # data = order_dict
    #     # data = {'sku':{'name':1,'name':2}}
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         # ser = OrderListSerializer({'status': orderinfo.status, 'pay_method': OrderInfo.pay_method, 'orders': ordergoods})
    #         # ser = OrderGoodsSerializer({'orders':ordergoods})
    #         # serializer.data=ser.data
    #         return self.get_paginated_response(serializer.data)
    #
    #     # serializer = self.get_serializer(queryset, many=True)
    #
    #     ser = OrderListSerializer({'status':orderinfo.status,'pay_method':OrderInfo.pay_method,'orders':ordergoods})
    #     ser.is_valid(raise_exception=True)
    #     return Response(ser.validated_data)

    # serializer_class = OrderSaveSerializer

    def get_serializer_class(self):

        if self.request.method == 'POST':
            return OrderSaveSerializer
        else:
            return OrderListSerializer


class OrdersGoodShowCommentView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self,request,order_id):

        order = OrderGoods.objects.filter(order=order_id,is_commented=False)

        # ser = OrderGoodsSerializer(data=order,many=True)
        ser = OrderGoodsSerializer(order,many=True)
        # ser.is_valid()

        return Response(ser.data)

class OrdersGoodCommentView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self,request,order_id):

        data = request.data
        # order = data.get('order')
        sku = data.get('sku')
        try:
            order = OrderGoods.objects.get(order=order_id,sku=sku)
        except:
            return Response({'message':'订单号不存在'})
        ser = UpdateCommentSerializer(order,data=data)
        ser.is_valid(raise_exception=True)
        ser.save()

        return Response('ok')

    # serializer_class = UpdateCommentSerializer
    #
    # def get_queryset(self):
    #
    #     order_id = self.kwargs['order_id']
    #     try:
    #         order = OrderGoods.objects.filter(order=order_id)
    #     except:
    #         return Response({'message':'订单号不存在'})
    #
    #     return order


